using GroupSix.Domain.Entity.App;
using GroupSix.Domain.Repositories;
using GroupSix.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace GroupSix.Infrastructure.Reposoitories;

public class UserRepository : EfRepository<GsUser>, IUserRepository
{
    public UserRepository(GroupSixDbContext dbContext) : base(dbContext)
    {
    }

    public async Task<GsUser?> GetByUsernameAsync(string username)
    {
        return await _tb.FirstOrDefaultAsync(u => u.Username == username && !u.IsDeleted);
    }

    public async Task<GsUser?> GetByEmailAsync(string email)
    {
        return await _tb.FirstOrDefaultAsync(u => u.Email == email && !u.IsDeleted);
    }

    public async Task<bool> IsUsernameExistsAsync(string username)
    {
        return await _tb.AnyAsync(u => u.Username == username && !u.IsDeleted);
    }

    public async Task<bool> IsEmailExistsAsync(string email)
    {
        return await _tb.AnyAsync(u => u.Email == email && !u.IsDeleted);
    }
    
    public async Task<List<GsUserRole>> GetUserRolesAsync(Guid userId)
    {
        return await _db.GsUserRoles
            .Include(ur => ur.Role)
            .Where(ur => ur.UserId == userId && !ur.IsDeleted)
            .ToListAsync();
    }
    
    public async Task<List<GsUserRole>> GetUserRolesByRoleIdAsync(Guid roleId)
    {
        return await _db.GsUserRoles
            .Include(ur => ur.User)
            .Where(ur => ur.RoleId == roleId && !ur.IsDeleted)
            .ToListAsync();
    }
    
    public async Task AssignRolesAsync(Guid userId, List<GsUserRole> userRoles)
    {
        await _db.GsUserRoles.AddRangeAsync(userRoles);
        await _db.SaveChangesAsync();
    }
    
    public async Task UpdateUserRolesAsync(Guid userId, List<GsUserRole> userRoles)
    {
        // 先删除现有角色
        var existingRoles = await _db.GsUserRoles
            .Where(ur => ur.UserId == userId)
            .ToListAsync();
        
        _db.GsUserRoles.RemoveRange(existingRoles);
        
        // 添加新角色
        await _db.GsUserRoles.AddRangeAsync(userRoles);
        
        await _db.SaveChangesAsync();
    }
    
    public async Task UpdateUserRolesAsync(List<GsUserRole> userRoles)
    {
        foreach (var userRole in userRoles)
        {
            _db.GsUserRoles.Update(userRole);
        }
        await _db.SaveChangesAsync();
    }
} 